package com.example.easydownloadback.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.easydownloadback.domin.File;
import com.example.easydownloadback.domin.FileType;
import com.example.easydownloadback.domin.ResponseResult;
import com.example.easydownloadback.mapper.FileTypeMapper;
import com.example.easydownloadback.service.FileAndTypeService;
import com.example.easydownloadback.service.FileTypeService;
import com.example.easydownloadback.util.Code;
import com.example.easydownloadback.util.RedisIdWorker;
import com.example.easydownloadback.util.RedisPrefix;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class FileTypeServiceImpl extends ServiceImpl<FileTypeMapper, FileType> implements FileTypeService {

    @Autowired
    private FileAndTypeService fileAndTypeService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public ResponseResult<List<FileType>> listFileType() {
        List<FileType> list = list();
        return new ResponseResult<List<FileType>>(Code.success, list);
    }

    @Override
    public ResponseResult<List<Map<String, String>>> listSimpleFileType() {
        List<FileType> list = list();
        List<Map<String, String>> maps = new ArrayList<>();
        for (FileType fileType : list) {
            Map<String, String> map = new HashMap<>(2);
            map.put("value", fileType.getTypeName());
            map.put("label", fileType.getTypeName());
            maps.add(map);
        }
        return new ResponseResult<List<Map<String, String>>>(Code.success, maps);
    }

    @Override
    public String getIdByTypeName(String name) {
        FileType one = query().select("id").eq("type_name", name).one();
        return one == null ? null : one.getId();
    }

    @Override
    public String getTypeNameById(String id) {
        return query().select("type_name").eq("id", id).one().getTypeName();
    }

    @Override
    public ResponseResult<List<String>> getFileTypeListByFileId(String fileId) {
        List<String> typeIdByFileId = fileAndTypeService.getTypeIdByFileId(fileId);
        if (typeIdByFileId == null || typeIdByFileId.isEmpty()) {
            return new ResponseResult<>(Code.success, Collections.emptyList());
        }
        List<String> resultList = new ArrayList<>(typeIdByFileId.size());
        for (String typeId : typeIdByFileId) {
            String typeNameById = this.getTypeNameById(typeId);
            resultList.add(typeNameById);
        }
        return new ResponseResult<>(Code.success, resultList);
    }

    @Override
    @Transactional
    public ResponseResult addFileType(FileType fileType) {
        RLock lock = redissonClient.getLock(RedisPrefix.LOCK_FILE_TYPE_KEY + fileType.getTypeName());
        // 获取分布式锁
        boolean isLock = lock.tryLock();
        // 获取锁失败也证明其它人正在添加；查询该分区是否存在
        if (!isLock || isFileTypeByTypeName(fileType.getTypeName())) {
            return new ResponseResult(Code.error, "已经添加过该分区了！");
        }
        try {
            // 创建该分区
            String id = redisIdWorker.nextId(RedisPrefix.FILE_TYPE_KEY);
            fileType.setId(id);
            save(fileType);
        } finally {
            lock.unlock();
        }
        return new ResponseResult<>(Code.success, "添加分区成功！");
    }

    @Override
    public boolean isFileTypeByTypeName(String typeName) {
        return query().eq("type_name", typeName).count() > 0;
    }

    @Override
    public ResponseResult<IPage<FileType>> listPageFileType(Integer pageNum, Integer pageSize, String selectValue) {
        IPage<FileType> page = new Page<>(pageNum, pageSize);
        IPage<FileType> resultPage = query().like(StrUtil.isNotBlank(selectValue), "type_name", selectValue).page(page);
        return new ResponseResult<>(Code.success, resultPage);
    }

    @Override
    public ResponseResult deleteFileTypeById(String id) {
        if (fileAndTypeService.existenceFileAndTypeByTypeId(id)) {
            return new ResponseResult<>(Code.error, "该分区关联着部分文件，请先管理好这些文件！");
        }
        boolean success = remove(new QueryWrapper<FileType>().eq("id", id));
        if (success) {
            return new ResponseResult<>(Code.success, "删除该分区完成！");
        }
        return new ResponseResult<>(Code.error, "删除异常！");
    }
}
